import { defineStore } from 'pinia';
import { 
  getSessionList, 
  getChatHistory, 
  sendMessage, 
  markAsRead, 
  deleteSession,
  deleteMessagesBySessionId,
  deleteMessagesByUserId
} from '../api/chat.js';

export const useChatStore = defineStore('chat', {
  state: () => ({
    // 聊天会话列表
    sessionList: [],
    // 当前聊天记录
    currentMessages: [],
    // 当前聊天对象ID
    currentTargetId: null,
    // 加载状态
    loading: false,
    // 是否正在发送消息
    sending: false,
    // 错误信息
    error: null
  }),

  getters: {
    // 获取会话列表
    getSessions: (state) => state.sessionList,
    // 获取当前聊天记录
    getCurrentMessages: (state) => state.currentMessages,
    // 获取当前聊天对象ID
    getCurrentTargetId: (state) => state.currentTargetId,
    // 获取加载状态
    isLoading: (state) => state.loading,
    // 获取发送状态
    isSending: (state) => state.sending,
    // 获取未读消息总数
    getUnreadCount: (state) => {
      return state.sessionList.reduce((total, session) => total + (session.unreadCount || 0), 0);
    }
  },

  actions: {
    // 加载会话列表
    async loadSessionList() {
      try {
        this.loading = true;
        const res = await getSessionList();
        if (res.code === 200) {
          this.sessionList = res.data;
        }
        return res;
      } catch (error) {
        console.error('获取会话列表失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 加载聊天记录
    async loadChatHistory(targetId) {
      try {
        this.loading = true;
        // 确保targetId是数字类型
        targetId = parseInt(targetId) || 0;
        if (!targetId) {
          throw new Error('无效的聊天对象ID');
        }
        
        this.currentTargetId = targetId;
        const res = await getChatHistory(targetId);
        if (res.code === 200) {
          this.currentMessages = res.data;
          // 自动标记为已读
          await this.markMessagesAsRead(targetId);
        }
        return res;
      } catch (error) {
        console.error('获取聊天记录失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 发送消息
    async sendNewMessage(messageDTO) {
      try {
        this.sending = true;
        console.log('准备发送消息，数据:', messageDTO);
        
        // 简化数据处理，防止复杂操作导致异常
        const sendData = {
          ...messageDTO
        };
        
        // 直接调用API，让API内部处理类型转换
        const res = await sendMessage(sendData);
        console.log('消息发送结果:', res);
        
        if (res && res.code === 200) {
          // 发送成功后，将新消息添加到当前聊天记录
          const newMessage = {
            id: res.data || Date.now(), // 如果后端未返回ID，使用时间戳
            ...messageDTO,
            sendTime: new Date().toISOString(),
            isRead: false
          };
          this.currentMessages.push(newMessage);
          // 更新会话列表
          await this.loadSessionList();
        } else {
          console.error('发送消息失败，服务器响应:', res);
          throw new Error(res?.msg || '发送失败');
        }
        return res;
      } catch (error) {
        console.error('发送消息异常:', error);
        throw error;
      } finally {
        this.sending = false;
      }
    },

    // 标记消息为已读
    async markMessagesAsRead(targetId) {
      try {
        // 确保targetId是数字类型
        targetId = parseInt(targetId) || 0;
        if (!targetId) return;
        
        const res = await markAsRead(targetId);
        if (res.code === 200) {
          // 更新本地会话的未读数
          const session = this.sessionList.find(s => s.targetId === targetId);
          if (session) {
            session.unreadCount = 0;
          }
        }
        return res;
      } catch (error) {
        console.error('标记已读失败:', error);
        throw error;
      }
    },

    // 删除会话
    async removeSession(sessionId) {
      try {
        // 确保sessionId是数字类型
        sessionId = parseInt(sessionId) || 0;
        if (!sessionId) return;
        
        const res = await deleteSession(sessionId);
        if (res.code === 200) {
          // 从本地会话列表中移除
          this.sessionList = this.sessionList.filter(s => s.id !== sessionId);
          // 如果是当前会话，清空聊天记录
          if (this.currentTargetId === sessionId) {
            this.currentMessages = [];
            this.currentTargetId = null;
          }
        }
        return res;
      } catch (error) {
        console.error('删除会话失败:', error);
        throw error;
      }
    },

    // 删除指定会话的所有聊天记录
    async deleteMessagesBySession(sessionId) {
      try {
        // 确保sessionId是数字类型
        sessionId = parseInt(sessionId) || 0;
        if (!sessionId) return;
        
        const res = await deleteMessagesBySessionId(sessionId);
        if (res.code === 200) {
          // 如果是当前会话，清空聊天记录
          if (this.currentTargetId === sessionId) {
            this.currentMessages = [];
          }
        }
        return res;
      } catch (error) {
        console.error('删除会话消息失败:', error);
        throw error;
      }
    },

    // 删除与指定用户的所有聊天记录
    async deleteMessagesByUser(targetId) {
      try {
        // 确保targetId是数字类型
        targetId = parseInt(targetId) || 0;
        if (!targetId) return;
        
        const res = await deleteMessagesByUserId(targetId);
        if (res.code === 200) {
          // 如果是当前聊天用户，清空聊天记录
          if (this.currentTargetId === targetId) {
            this.currentMessages = [];
          }
        }
        return res;
      } catch (error) {
        console.error('删除用户消息失败:', error);
        throw error;
      }
    },

    // 添加新消息（用于websocket消息推送）
    addNewMessage(message) {
      // 如果是当前聊天对象的消息，直接添加到聊天记录
      if (message.senderId === this.currentTargetId) {
        this.currentMessages.push(message);
      }
      // 更新会话列表中的最新消息和未读数
      const session = this.sessionList.find(s => s.targetId === message.senderId);
      if (session) {
        session.lastMessage = message.content;
        session.lastTime = message.sendTime;
        session.unreadCount = (session.unreadCount || 0) + 1;
      }
    },

    // 清空当前聊天记录
    clearCurrentChat() {
      this.currentMessages = [];
      this.currentTargetId = null;
    }
  }
});
